package com.xujp.pagment18002.controller;


import com.xujp.common.entity.CommonResult;
import com.xujp.common.entity.Payment;
import com.xujp.pagment18002.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author xujp
 * @date 2021/04/29/0029 17:00
 * @description:
 */
@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentService paymentService;


    @Value("${server.port}")
    private String serverPort;

    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/insert")
    public CommonResult insert(@RequestBody Payment payment) {
        int insert = paymentService.insert(payment);
        log.info("******插入结果：" + insert);
        if (insert > 0) {

            return new CommonResult(200, "插入成功，端口：" + serverPort, insert, null);
        } else {
            return new CommonResult(444, "插入失败", null, null);
        }
    }

    @PostMapping("/lb1/query")
    public CommonResult query() {
        List<Payment> query = paymentService.query();
        if (query.size() >= 0) {
            log.info("****查询成功，查询结果集数量为：" + query.size());
            return new CommonResult(200, "查询成功，端口：" + serverPort, null, query);
        } else {
            log.info("******查询结果为空");
            return new CommonResult(200, "查询成功", null, null);
        }
    }



    @PostMapping("/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("****service: " + service);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance instance : instances) {
            log.info("host: " + instance.getHost() + "\t" + "instanceid: " + instance.getInstanceId() + "\t port: " + instance.getPort() + "\t url: " + instance.getUri());
        }
        return this.discoveryClient;
    }

}
